import { useRef } from 'preact/hooks';
import { useSignalEffect } from '@preact/signals';
import { Namespace } from '../../utils';
import { AiChatController } from '../../controller';
import { IChatToolbarItem } from '../../interface';
import { ChatMessageItem } from '../chat-message-item/chat-message-item';
import { ChatToolbar } from '../chat-toolbar/chat-toolbar';
import './chat-messages.scss';

export interface ChatMessageProps {
  /**
   * 单实例聊天总控
   *
   * @author chitanda
   * @date 2023-10-13 17:10:43
   * @type {AiChatController}
   */
  controller: AiChatController;

  /**
   * 工具项集合
   *
   * @type {IChatToolbarItem[]}
   * @memberof ChatMessageProps
   */
  toolbarItems?: IChatToolbarItem[];
}

const ns = new Namespace('chat-messages');

export const ChatMessages = (props: ChatMessageProps) => {
  const ref = useRef<HTMLDivElement>(null);

  const messages = props.controller.messages;

  useSignalEffect(() => {
    if (ref.current && messages.value.length > 0) {
      ref.current.scrollTop = ref.current.scrollHeight;
    }
  });

  return (
    <div ref={ref} className={ns.b()}>
      {messages.value.map(message => {
        const size = message.content?.length || 0;
        return (
          <ChatMessageItem
            size={size}
            message={message}
            key={message.messageid}
            controller={props.controller}
          >
            <ChatToolbar
              data={message}
              type='content'
              items={props.toolbarItems}
              controller={props.controller}
            />
          </ChatMessageItem>
        );
      })}
    </div>
  );
};
